﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using WcfBookingService.Properties;

namespace WcfBookingService.DataLayer
{
    public class DbHandler
    {
        public SqlConnection Connection { get; internal set; }
        public SqlCommand Command { get; set; }

        public DbHandler()
        {
            Connection = new SqlConnection(Settings.Default.ConnectionString);
        }
        
        public SqlParameter AddParameter(String name, dynamic value)
        {
            //Make sure we set the null to be DBNull!
            //http://stackoverflow.com/questions/6778483/the-parameterized-query-which-was-not-supplied
            if (value == null)
                value = DBNull.Value;

            return Command.Parameters.Add(new SqlParameter("@"+name, value));
        }

        public void AddCommand(String cmdText)
        {
            Command = CreateCommand(cmdText);
        }

        public SqlCommand CreateCommand(String cmdText)
        {
            return new SqlCommand(@cmdText, Connection);
        }

        public void Open()
        {
            Connection.Open();
        }

        public void Close()
        {
            Connection.Close();
        }

        public static T ParseValue<T>(System.Data.SqlClient.SqlDataReader reader, string column)
        {
            T result = default(T);

            if (!reader.IsDBNull(reader.GetOrdinal(column)))
                result = (T)reader.GetValue(reader.GetOrdinal(column));

            return result;
        }
    }
}